/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package anbserver;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author An
 */
public class ANBankImpl extends UnicastRemoteObject implements bankinterface.BankInterface {

    private String name;
    private int pin;
    private float balance;
    private ConnectDB cdb = null;
    private Connection con;
    private Statement st;
    private ResultSet rs;

    @Override
    public String toString() {
        return "ANBankImpl{" + "name=" + name + ", pin=" + pin + ", balance=" + balance + '}';
    }

    public ANBankImpl(String name, int pin, float balance) throws RemoteException {
        this.balance = balance;
        this.name = name;
        this.pin = pin;
    }

    public ANBankImpl() throws RemoteException {
    }

    public ANBankImpl(float balance) throws RemoteException {
        this.balance = balance;
    }

    public void setBalance(float balance) {
        this.balance = balance;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPin() {
        return pin;
    }

    public void setPin(int pin) {
        this.pin = pin;
    }

    @Override
    public boolean logIn(String name, String pin) throws RemoteException {

        try {
            cdb = new ConnectDB();
            con = cdb.getConnection();
            st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            String query = "SELECT accName,pin FROM account";
            rs = st.executeQuery(query);
            while (rs.next()) {
                if ((rs.getString("accName").equalsIgnoreCase(name)) && (rs.getString("pin").equalsIgnoreCase(pin))) {
                    con.close();
                    return true;
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (SQLException ex) {
                Logger.getLogger(ANBankImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        //   JOptionPane.showMessageDialog(null, "Account not available !");
        return false;
    }

    public float getBalance() {
        return balance;
    }

    @Override
    public float getCurrentBalance(String name) throws RemoteException {
        float bl = 0;
        try {
            cdb = new ConnectDB();
            con = cdb.getConnection();
            st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            String query = "SELECT balance FROM account WHERE accName='" + name + "'";
            rs = st.executeQuery(query);
            // while (rs.next()) {
            rs.next();
            bl = rs.getFloat("balance");
            con.close();
            return bl;
            //  }
        } catch (Exception ex) {
            // return false;
            ex.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (SQLException ex) {
                Logger.getLogger(ANBankImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return bl;
    }

    @Override
    public boolean transfer(String from, String to, float quantity) throws RemoteException {
        Savepoint sv = null;
        try {
            cdb = new ConnectDB();
            con = cdb.getConnection();
            con.setAutoCommit(false);

            String send = "UPDATE  account"
                    + " SET balance = balance -" + quantity
                    + "WHERE accName='" + from + "'";
            String receiv = "UPDATE  account"
                    + " SET balance = balance +" + quantity
                    + "WHERE accName='" + to + "'";
            sv = con.setSavepoint("Save_1");
            st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            st.addBatch(send);
            st.addBatch(receiv);
            int[] i = st.executeBatch();
            //check
            String query = "SELECT balance FROM account WHERE accName='" + from + "'";
            rs = st.executeQuery(query);
            // while (rs.next()) {
            rs.next();
            float bl = rs.getFloat("balance");
            if (bl < 0) {
                con.rollback(sv);
                return false;
            }
            if (i[0] == Statement.EXECUTE_FAILED || i[1] == Statement.EXECUTE_FAILED) {
                con.rollback(sv);
                return false;
            }
            //check account exist
            boolean exist = false;
            String check = "SELECT accName FROM account";
            rs = st.executeQuery(check);
            while (rs.next()) {
                if (rs.getString("accName").equalsIgnoreCase(to)) {
                    exist = true;
                }
            }
            if (!exist) {
                con.rollback(sv);
                return false;
            }
            con.commit();
            con.setAutoCommit(true);
            con.close();
            return true;
            //   JOptionPane.showMessageDialog(null, "Transfer successful !");


        } catch (Exception ex) {
            try {
                con.rollback(sv);
                return false;
            } catch (SQLException ex1) {
                Logger.getLogger(ANBankImpl.class.getName()).log(Level.SEVERE, null, ex1);
            }
            ex.printStackTrace();
        } finally {
            try {
                con.setAutoCommit(true);
                con.close();
            } catch (SQLException ex) {
                Logger.getLogger(ANBankImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return false;
    }

    @Override
    public boolean changePinNumber(String name, String newPin) throws RemoteException {

        try {
            cdb = new ConnectDB();
            con = cdb.getConnection();
            st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            String query = "SELECT accName,pin FROM account";
            rs = st.executeQuery(query);
            while (rs.next()) {
                if ((rs.getString("accName").equalsIgnoreCase(name))) {

                    query = "UPDATE  account"
                            + " SET pin = '" + newPin
                            + "' WHERE accName='" + name + "'";
                    st.executeUpdate(query);
                    con.close();
                    return true;
                }
            }

        } catch (Exception ex) {
            // return false;
            ex.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (SQLException ex) {
                Logger.getLogger(ANBankImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return false;
    }
    /**
     * @param args the command line arguments
     */
}
